package com.taiji.dicom4cloud.smart.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taiji.dicom4cloud.smart.dao.FtpFileMapper;
import com.taiji.dicom4cloud.smart.model.entity.FtpFile;
import com.taiji.dicom4cloud.smart.service.FtpFileService;
import com.taiji.dicom4cloud.smart.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

/**
 * @ClassName FtpFileServiceImpI
 * @Description
 * @Author HX
 * @Date 2021/9/27 17:59
 **/
@Slf4j
@Service
public class FtpFileServiceImpI extends ServiceImpl<FtpFileMapper,FtpFile> implements FtpFileService {

    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public FtpFile saveFtpFile(File file,Integer recordId) {
        String filePath = file.getParentFile().getPath();
        String temp[] = filePath.split(Matcher.quoteReplacement(File.separator));
        String deviceId = temp[temp.length - 1];
        FtpFile ftpFile = new FtpFile();
        ftpFile.setDeviceId(deviceId);
        ftpFile.setFileName(file.getName());
        ftpFile.setFilePath(file.getPath());
        ftpFile.setCreateTime(LocalDateTime.now());
        ftpFile.setFileType("dav");
        ftpFile.setRecordId(recordId);
        this.saveOrUpdate(ftpFile);
        return ftpFile;
    }

    @Override
    public Boolean saveTranPath(Integer recordId){
        FtpFile ftpFile = this.getOne(Wrappers.<FtpFile>lambdaQuery().eq(FtpFile::getRecordId,recordId));
        if(ObjectUtil.isNotNull(ftpFile)){
            log.info("转换结果写入数据库成功");
            Map<String, Object> map = sysConfigService.getConfigByKeys("ftp_dir");
            String path = ftpFile.getFilePath();
            path = path.replace(".dav",".mp4");
            path = path.replace(map.get("ftp_dir").toString(),"/mp4");
            ftpFile.setTranPath(path);
            this.saveOrUpdate(ftpFile);
        }
        return Boolean.TRUE;
    }


    @Override
    public Page getFtpFilePage(Page page, FtpFile ftpFile) {
        Page page1 = this.page(page, Wrappers.<FtpFile>lambdaQuery().eq(FtpFile::getDeviceId,ftpFile.getDeviceId()));
        return page1;
    }

    @Override
    public List<FtpFile> listFtpFile(String startTime, String deviceId) {
        Map<String, Object> map = sysConfigService.getConfigByKeys("error_range");
        Integer rangeNumber = Integer.parseInt(map.get("error_range").toString()) ;

        try {
            long newTime = dateToStamp(startTime);
            String endTime = stampToDate(newTime+rangeNumber+"");
            List<FtpFile> ftpFiles = this.list(Wrappers.<FtpFile>lambdaQuery().eq(FtpFile::getDeviceId,deviceId)
                    .eq(FtpFile::getDeviceId,deviceId)
                    .apply( "date_format (create_time,'%Y-%m-%d %H:%i:%s') >= date_format('" + startTime + "','%Y-%m-%d %H:%i:%s')")
                    .apply( "date_format (create_time,'%Y-%m-%d %H:%i:%s') <= date_format('" + endTime + "','%Y-%m-%d %H:%i:%s')"));
            return ftpFiles;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 将时间转换为时间戳
     */
    public static long dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        return ts;
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
}
